export default {
	// 开启命名空间
	namespaced: true,
	state: {
		// 购物车地址
		address: JSON.parse(uni.getStorageSync("address") || "[]"),
		token: uni.getStorageSync("token") || "",
		userInfo: JSON.parse(uni.getStorageSync("userInfo") || "{}"),
		coupons: [],
		currentAddress: JSON.parse(uni.getStorageSync("currentAddress") || "{}"),
		addflag: false,
		currentAddressId: uni.getStorageSync("currentAddressId") || "",
		couponsPrice:0
	},
	mutations: {
		updateCouponsPrice(state, payload) {
			state.couponsPrice = payload
		},
		updateaddflag(state, payload) {
			state.addflag = payload
		},
		updateCurrentAddress(state, payload) {
			state.currentAddress = payload
			this.commit("m_user/saveCurrentAddressToStorage");
		},
		// 持久化存储当前地址信息
		saveCurrentAddressToStorage(state) {
			uni.setStorageSync('currentAddress', JSON.stringify(state.currentAddress));
		},
		// 更新优惠卷
		updateCoupons(state, payload) {
			state.coupons = payload
		},
		// 更新收货地址
		updateAddress(state, payload) {
			payload.forEach(item => {
				item.default_currentAddress = 0
			})
			console.log(payload)

			if (state.currentAddressId) {
				const defaultAddress = payload.find(item => {
					return item.id === state.currentAddressId
				})
				if(defaultAddress){
					defaultAddress.default_currentAddress = 1
				}
				// console.log(defaultAddress)
			} else {
				payload[0].default_currentAddress = 1
			}
			state.address = payload;
			// 持久化存储到本地
			this.commit("m_user/saveAddressToStorage");
		},
		// 修改默认地址
		updateDefault(state, payload) {
			state.address.forEach(item => {
				// default_status
				item.default_currentAddress = 0
			})
			let deAddress = state.address.find(item => {
				return item.id === payload.id
			})
			deAddress.default_currentAddress = 1
			this.commit("m_user/updateCurrentAddressId", payload.id)
			this.commit("m_user/saveAddressToStorage");
		},
		// 持久化存储地址信息
		saveAddressToStorage(state) {
			uni.setStorageSync('address', JSON.stringify(state.address));
		},
		// 更新 token
		updateToken(state, payload) {
			state.token = payload;
			// 持久化存储到本地
			this.commit("m_user/saveTokenToStorage");
		},
		// 更新 
		updateCurrentAddressId(state, payload) {
			state.currentAddressId = payload
			// 持久化存储到本地
			this.commit("m_user/savecurrentAddressIdToStorage");
		},
		savecurrentAddressIdToStorage(state) {
			uni.setStorageSync('currentAddressId', state.currentAddressId);
		},
		// 持久化存储 token
		saveTokenToStorage(state) {
			// console.log(state.token); //@log
			uni.setStorageSync('token', state.token);
		},
		// 更新用户的基本信息
		updateUserInfo(state, payload) {
			state.userInfo = payload;
			// 持久化存储到本地
			this.commit("m_user/saveUserInfoToStorage");
		},
		// 持久化存储用户信息
		saveUserInfoToStorage(state) {
			uni.setStorageSync('userInfo', JSON.stringify(state.userInfo));
		},

	}

}
